package com.steven.im.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.base.BaseActivity;
import com.steven.im.entity.IMMsgInfo;
import com.steven.im.entity.ImBaseEntity;
import com.steven.im.entity.mobileLoginBo;
import com.steven.im.manager.DBManager;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.net.Url;
import com.steven.im.utils.DataCheckUtils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.TitleBuilder;
import com.steven.im.utils.ToastUtil;
import com.steven.im.webSocket.WebSocketClient;
import com.steven.im.widget.CountTimer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

public class ImLoginActivity extends BaseActivity {
    private String smsKey = "";//发送短信返回的key
    CountTimer countTimer;
    @BindView(R.id.et_phone)//手机号
            EditText et_phone;
    @BindView(R.id.et_phoneCode)//手机验证码
            EditText et_phoneCode;
    @BindView(R.id.tv_getcode)//获取验证码
            TextView tvGetcode;
    @BindView(R.id.ed_referralCode)//推介人代码 目前隐藏
            EditText ed_referralCode;
    @BindView(R.id.tv_login)
    TextView tv_login;

    @Override
    public void setListen() {
        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (et_phone.getText().toString().length() > 0) {
                    tv_login.setBackgroundResource(R.drawable.bg_btn);
                } else {
                    if (("").equals(et_phoneCode.getText().toString()) && ("").equals(et_phoneCode.getText().toString())) {
                        tv_login.setBackgroundResource(R.drawable.bg_btn_gray);
                    }
                }
            }
        });
        et_phoneCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (et_phoneCode.getText().toString().length() == 0) {
                    if (("").equals(et_phoneCode.getText().toString()) && ("").equals(et_phoneCode.getText().toString())) {
                        tv_login.setBackgroundResource(R.drawable.bg_btn_gray);
                    }
                } else {
                    tv_login.setBackgroundResource(R.drawable.bg_btn);
                }
            }
        });
    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_im_login;
    }

    @Override
    public void initView() {

        countTimer = new CountTimer(tvGetcode);
    }

    @Override
    public void initData() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countTimer != null) {
            countTimer.cancel();
            tvGetcode.setEnabled(true);
            tvGetcode.setText("获取验证码");
        }
    }


    @OnClick({R.id.tv_getcode, R.id.tv_login, R.id.tv_xieyi})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_getcode://获取验证码
                if (!("").equals(et_phone.getText().toString()) && DataCheckUtils.isCellphone(et_phone.getText().toString())) {
                    sendVerify();
                } else {
                    ToastUtil.showShort(App.getContext(), "不合法的手机号！");
                }
                break;
            case R.id.tv_login://注册
                SPUtils.put(this, "uID", "000");
                //添加信息
                List<IMMsgInfo> list = new ArrayList<>();
                IMMsgInfo imMsgInfo = new IMMsgInfo();
                imMsgInfo.setF("111");
                imMsgInfo.setT("000");
                imMsgInfo.setuName("周杰伦");
                imMsgInfo.setChatType("2");
                imMsgInfo.setAvatarUrl("http://imgsrc.baidu.com/forum/w%3D580%3B/sign=3d5464e3922bd40742c7d3f54bb29c51/f703738da9773912876b7faafd198618377ae2a8.jpg");
                imMsgInfo.setContent("你在干嘛呢，小伙，约不约！");
                imMsgInfo.setMsgType("1");
                imMsgInfo.setMsgDate("1565752969011");
                list.add(imMsgInfo);

                IMMsgInfo imMsgInfo1 = new IMMsgInfo();
                imMsgInfo1.setF("111");
                imMsgInfo1.setT("000");
                imMsgInfo1.setuName("黄金叶");
                imMsgInfo1.setChatType("2");
                imMsgInfo1.setAvatarUrl("http://imgsrc.baidu.com/forum/w%3D580%3B/sign=3d5464e3922bd40742c7d3f54bb29c51/f703738da9773912876b7faafd198618377ae2a8.jpg");
                imMsgInfo1.setContent("利群真好！");
                imMsgInfo1.setMsgType("1");
                imMsgInfo1.setMsgDate("1565752969010");
                list.add(imMsgInfo1);

                IMMsgInfo imMsgInfo2 = new IMMsgInfo();
                imMsgInfo2.setF("222");
                imMsgInfo2.setT("000");
                imMsgInfo2.setuName("周杰伦");
                imMsgInfo2.setChatType("2");
                imMsgInfo2.setAvatarUrl("http://imgsrc.baidu.com/forum/w%3D580%3B/sign=3d5464e3922bd40742c7d3f54bb29c51/f703738da9773912876b7faafd198618377ae2a8.jpg");
                imMsgInfo2.setContent("你在干嘛呢，小伙，约不约！");
                imMsgInfo2.setMsgType("1");
                imMsgInfo2.setMsgDate("1565753030738");
                list.add(imMsgInfo2);

                IMMsgInfo imMsgInfo3 = new IMMsgInfo();
                imMsgInfo3.setF("111");
                imMsgInfo3.setT("000");
                imMsgInfo3.setuName("黄金叶");
                imMsgInfo3.setChatType("2");
                imMsgInfo3.setAvatarUrl("http://imgsrc.baidu.com/forum/w%3D580%3B/sign=3d5464e3922bd40742c7d3f54bb29c51/f703738da9773912876b7faafd198618377ae2a8.jpg");
                imMsgInfo3.setContent("利群真好！");
                imMsgInfo3.setMsgType("1");
                imMsgInfo3.setMsgDate("1565753040783");
                list.add(imMsgInfo3);

                IMMsgInfo imMsgInfo4 = new IMMsgInfo();
                imMsgInfo4.setF("111");
                imMsgInfo4.setT("000");
                imMsgInfo4.setuName("黄金叶");
                imMsgInfo4.setChatType("2");
                imMsgInfo4.setAvatarUrl("http://imgsrc.baidu.com/forum/w%3D580%3B/sign=3d5464e3922bd40742c7d3f54bb29c51/f703738da9773912876b7faafd198618377ae2a8.jpg");
                imMsgInfo4.setContent("利群真好，是不是啊！");
                imMsgInfo4.setMsgType("1");
                imMsgInfo4.setMsgDate("1565753801555");
                list.add(imMsgInfo4);
                DBManager.insert(list);


                //得判断
//                if (("").equals(et_phone.getText().toString())) {
//                    ToastUtil.showShort(App.getContext(), "请输入手机号！");
//                } else if (("").equals(et_phoneCode.getText().toString())) {
//                    ToastUtil.showShort(App.getContext(), "请输入手机验证码！");
//                } else {
//                    login();
//                }
                startActivity(new Intent(ImLoginActivity.this, MainActivity.class));
                break;
            case R.id.tv_xieyi:
                startActivity(new Intent(ImLoginActivity.this, WebActivity.class).putExtra("title", "注册协议").putExtra("url", Url.REGISTER_AGREEMENT));
                break;
        }
    }


    //用户登录
    private void login() {

        if (!DataCheckUtils.isCellphone(et_phone.getText().toString())) {
            Toast.makeText(ImLoginActivity.this, "请输入正确的手机号！", Toast.LENGTH_SHORT).show();
        } else {
            String appId = "android";
            String code = et_phoneCode.getText().toString();
            String codeKey = smsKey;
            String mobile = et_phone.getText().toString();
            int recommendId = 1321353;//推介码
            mobileLoginBo imLoginBody = new mobileLoginBo();
            imLoginBody.setAppid(appId);
            imLoginBody.setCode(code);
            imLoginBody.setCodekey(codeKey);
            imLoginBody.setMobile(mobile);
            imLoginBody.setRecommendId(recommendId);

            Task.getApiService().imLogin(imLoginBody).enqueue(new MyCallback<ImBaseEntity>(ImLoginActivity.this) {
                @Override
                protected void onSuccess(Response<ImBaseEntity> response) {
                    if ("1".equals(response.body().getCode())) {
                        String jsonStr = JSONObject.toJSONString(response.body().getData());
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        String accessToken = jsonObject.getString("accessToken");
                        String token = jsonObject.getString("token");
                        Integer userId = jsonObject.getInteger("userid");
                        SPUtils.put(App.getContext(), "accessToken", accessToken);
                        SPUtils.put(App.getContext(), "token", token);
                        SPUtils.put(App.getContext(), "userId", userId.toString());
                        //连接webSocket
                        WebSocketClient.getInstance().connectAsynchronously();
                        startActivity(new Intent(ImLoginActivity.this, MainActivity.class));
                        finish();
                    }
                }

                @Override
                protected void onFailure(Throwable t) {
                }
            });
        }
    }

    /**
     * 获取验证码
     */
    private void sendVerify() {
        countTimer.start();
        Task.getApiService().sendImPhoneCode(et_phone.getText().toString()).enqueue(new MyCallback<ImBaseEntity>(ImLoginActivity.this) {
            @Override
            protected void onSuccess(Response<ImBaseEntity> response) {
                if ("1".equals(response.body().getCode())) {
                    smsKey = response.body().getData().toString();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                ToastUtil.showShort(App.getContext(), "发送失败！");
            }
        });
    }
}
